package jjn.round1;

/**
 * @author Jjn
 * @since 2022-08-15 18:54
 */
public class SortingAlgorithm_MergeSort implements SortAlgorithm {
    
    @Override
    public void sort(int... nums) {
        mergeSort(nums, 0, nums.length - 1);
    }
    
    private void mergeSort(int[] array, int left, int right) {
        if (right <= left) {
            return;
        }
        int mid = (left + right) >> 1;
        mergeSort(array, left, mid);
        mergeSort(array, mid + 1, right);
        merge(array, left, mid, right);
    }
    
    private void merge(int[] array, int left, int mid, int right) {
        int[] temp = new int[right - left + 1];
        int i = left, j = mid + 1, k = 0;
        while (i <= mid && j <= right) {
            temp[k++] = array[i] <= array[j] ? array[i++] : array[j++];
        }
        while (i <= mid) {
            temp[k++] = array[i++];
        }
        while (j <= right) {
            temp[k++] = array[j++];
        }
        for (int p = 0; p < temp.length; p++) {
            array[left + p] = temp[p];
        }
        // 也可以用 System.arraycopy(a, start1, b, start2, length)
    }
    
    @Override
    public String getName() {
        return "Merge sort";
    }
}
